package com.CTAtracker.android.Adapters;

import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.TextView;

import com.CTAtracker.android.R;
import com.CTAtracker.android.DAO.FavoriteDataSource;
import com.CTAtracker.android.Models.StopETA;
import com.CTAtracker.android.XML.InternetETA;
import com.CTAtracker.android.api.CTAResClientUsage;

/**
 * This class is an adapter for Stops in the Station activity
 * It also implement Observer to be able to retrieve the data from Internet
 */
public class StopItemAdapter extends ArrayAdapter<StopETA> implements Observer {

	/**
	 * The layout to inflate
	 */
	private LayoutInflater _layoutInflater = null;
	/**
	 * The id of the resource
	 */
	private int _resourceId = 0;
	/**
	 * The list of stop to adapt to the view
	 */
	private ArrayList<StopETA> _listStop;
	/**
	 * The instance of the CTAResClientUsage
	 */
	private CTAResClientUsage _ctaResClientUsage;
		
	/**
	 * Constructor of the class. Instance the attribute and call the super method.
	 * @param context The context of the application
	 * @param resourceId The id of the resource to inflate 
	 * @param listStop the list of stop to adapt to the view
	 */
	public StopItemAdapter(Context context, int ResourceId,
			ArrayList<StopETA> listStop) {
		super(context, ResourceId, 0, listStop);
		_listStop = new ArrayList<StopETA>();
		_listStop = listStop;
		_resourceId = ResourceId; 
		_layoutInflater = LayoutInflater.from(context);
		if (isOnline()){
			_ctaResClientUsage = new CTAResClientUsage(this);
			_ctaResClientUsage.getNextArrivalStation(_listStop.get(0).get_parentId(), 
					_listStop.get(0).getColorAPI());	
		}else {
			// TODO Message Error
		}
	}

	/**
	 * This method is called every time we want to display the view
	 * It prints the next time of arrival 
	 */
	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {

		final StopETA stop = _listStop.get(position);
		convertView = _layoutInflater.inflate(_resourceId, parent, false);
		
		TextView nameStop = (TextView) convertView.findViewById(R.id.NameStopTextView);
		nameStop.setText(stop.getNameStop());

		ImageButton star = (ImageButton) convertView.findViewById(R.id.favorite);
		TextView infoStop = (TextView) convertView.findViewById(R.id.infoStop);
		
		if (stop.isFavorite()){
			star.setBackgroundResource(R.drawable.is_favorite);
		} else {
			star.setBackgroundResource(R.drawable.is_not_favorite);
		}
			
		if (stop.get_listInternetETA().isEmpty()){
			if (isOnline()){
				infoStop.setText("Retrieving Data from the server");
			}else {
				infoStop.setText("Impossible to retrieve data from the server\nPlease Check your connection parameters");
			}
		}else {
			infoStop.setText(stop.getETA());
		}
		
		star.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				changeDatabaseFavorite(v);
				notifyDataSetChanged();
			}

			private void changeDatabaseFavorite(View v) {
				FavoriteDataSource db = new FavoriteDataSource(getContext());
				db.open();
				if (db.isFavorite(stop.get_idStop())){
					db.delete(stop);
				}else {
					db.insert(stop);
				}
				db.close();
					
			}
		});
		
		return convertView;
	}

	/**
	 * This method is called by the class APIXmlParser to update the value of the next time of arrival 
	 */
	@SuppressWarnings("unchecked")
	@Override
	public synchronized void update(Observable observable, Object data) {
		ArrayList<InternetETA> list = (ArrayList<InternetETA>) data;
		
		for (int i=0; i<_listStop.size(); i++){
			_listStop.get(i).get_listInternetETA().clear();
		}
		
		for (int j=0; j< _listStop.size(); j++){
			for (int i=0; i<list.size(); i++){
				if (list.get(i).get_stpId() == _listStop.get(j).get_idStop()){
					_listStop.get(j).get_listInternetETA().add(list.get(i));
				}else {
					// Do nothing
				}	
			}
		}
		this.notifyDataSetChanged();
	}
	
	public boolean isOnline() {
	    ConnectivityManager cm =
	        (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo netInfo = cm.getActiveNetworkInfo();
	    if (netInfo != null && netInfo.isConnected()) {
	        return true;
	    }
	    return false;
	}
}
